package com.jww.servlet.provider;

import com.alibaba.fastjson.JSONArray;
import com.jww.pojo.Provider;
import com.jww.pojo.User;
import com.jww.service.provider.providerService;
import com.jww.service.provider.providerServiceImpl;
import com.jww.util.Constants;
import com.mysql.jdbc.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class ProviderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method != null && method.equals("query")) {
            this.query(req, resp);
        } else if (method != null && method.equals("add")) {
            this.add(req, resp);
        } else if (method != null && method.equals("view")) {
            this.getProviderId(req, resp, "providerview.jsp");
        } else if (method != null && method.equals("delprovider")) {
            this.deleteProviderById(req, resp);
        } else if (method != null && method.equals("modifysave")) {
            this.modifyProvider(req, resp);
        } else if (method != null && method.equals("modify")) {
            this.getProviderId(req, resp, "providermodify.jsp");
        } else if (method != null && method.equals("selectProCodeExist")) {
            this.selectProCodeExist(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    // 查询供应商信息
    public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String queryProCode = req.getParameter("queryProCode");
        String queryProName = req.getParameter("queryProName");

        List<Provider> providerList = new ArrayList<Provider>();
        providerService providerService = new providerServiceImpl();

        if (queryProCode == null) {
            queryProCode = "";
        }

        if (queryProName == null) {
            queryProName = "";
        }

        providerList = providerService.getProviderList(queryProName, queryProCode);
        req.setAttribute("queryProCode", queryProCode);
        req.setAttribute("queryProName", queryProName);
        req.setAttribute("providerList", providerList);

        // 返回前端
        req.getRequestDispatcher("providerlist.jsp").forward(req, resp);
    }

    // 添加供应商
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("add()================");
        String proCode = req.getParameter("proCode");
        String proName = req.getParameter("proName");
        String proContact = req.getParameter("proContact");
        String proPhone = req.getParameter("proPhone");
        String proAddress = req.getParameter("proAddress");
        String proFax = req.getParameter("proFax");
        String proDesc = req.getParameter("proDesc");

        // 后端验证：检查所有必填字段是否为空
        if (proCode == null || proCode.trim().isEmpty() ||
                proName == null || proName.trim().isEmpty() ||
                proContact == null || proContact.trim().isEmpty() ||
                proPhone == null || proPhone.trim().isEmpty() ||
                proAddress == null || proAddress.trim().isEmpty()) {

            // 设置错误信息并返回添加页面
            req.setAttribute("error", "所有必填字段都不能为空或者为空格！");

            // 将用户已填写的数据重新设置到request中，实现数据回显
            Provider providerBack = new Provider();
            providerBack.setProCode(proCode != null ? proCode : "");
            providerBack.setProName(proName != null ? proName : "");
            providerBack.setProContact(proContact != null ? proContact : "");
            providerBack.setProPhone(proPhone != null ? proPhone : "");
            providerBack.setProAddress(proAddress != null ? proAddress : "");
            providerBack.setProFax(proFax != null ? proFax : "");
            providerBack.setProDesc(proDesc != null ? proDesc : "");

            req.setAttribute("provider", providerBack);
            req.getRequestDispatcher("provideradd.jsp").forward(req, resp);
            return;
        }

        // 检查供应商编码是否重复
        providerService providerService = new providerServiceImpl();
        Provider existingProvider = providerService.selectProCodeExist(proCode);
        if (existingProvider != null) {
            // 设置错误信息并返回添加页面
            req.setAttribute("error", "供应商编码已存在，请使用其他编码！");

            // 将用户已填写的数据重新设置到request中，实现数据回显
            Provider providerBack = new Provider();
            providerBack.setProCode(proCode);
            providerBack.setProName(proName);
            providerBack.setProContact(proContact);
            providerBack.setProPhone(proPhone);
            providerBack.setProAddress(proAddress);
            providerBack.setProFax(proFax);
            providerBack.setProDesc(proDesc);

            req.setAttribute("provider", providerBack);
            req.getRequestDispatcher("provideradd.jsp").forward(req, resp);
            return;
        }

        Provider provider = new Provider();
        provider.setProCode(proCode);
        provider.setProName(proName);
        provider.setProContact(proContact);
        provider.setProPhone(proPhone);
        provider.setProAddress(proAddress);
        provider.setProFax(proFax);
        provider.setProDesc(proDesc);
        provider.setCreationDate(new Date());
        provider.setCreatedBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());

        if (providerService.add(provider)) {
            resp.sendRedirect(req.getContextPath() + "/jsp/provider.do?method=query");
        } else {
            req.setAttribute("error", "添加供应商失败，请重试！");

            // 将用户已填写的数据重新设置到request中，实现数据回显
            req.setAttribute("provider", provider);
            req.getRequestDispatcher("provideradd.jsp").forward(req, resp);
        }
    }

    // 通过id查询单个供应商信息
    public void getProviderId(HttpServletRequest req, HttpServletResponse resp, String url)
            throws ServletException, IOException {
        String proid = req.getParameter("proid");
        if (!StringUtils.isNullOrEmpty(proid)) {
            providerService providerService = new providerServiceImpl();
            Provider provider = providerService.getProviderById(Integer.parseInt(proid));
            req.setAttribute("provider", provider);
            req.getRequestDispatcher(url).forward(req, resp);
        }
    }

    // 通过id查询单个供应商信息用于修改
    public void getProviderForModify(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String proid = req.getParameter("proid");
        if (!StringUtils.isNullOrEmpty(proid)) {
            providerService providerService = new providerServiceImpl();
            Provider provider = providerService.getProviderById(Integer.parseInt(proid));
            req.setAttribute("provider", provider);
            req.getRequestDispatcher("providermodify.jsp").forward(req, resp);
        }
    }

    // 通过id删除供应商信息
    public void deleteProviderById(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String proid = req.getParameter("proid");
        Integer delId = 0;
        try {
            delId = Integer.parseInt(proid);
        } catch (Exception e) {
            delId = 0;
        }

        HashMap<String, String> resultMap = new HashMap<>();
        if (delId <= 0) {
            resultMap.put("delResult", "notexist");
        } else {
            providerService providerService = new providerServiceImpl();
            boolean flag = providerService.deleteProviderById(delId);
            if (flag) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }
        // 返回前端
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 修改供应商信息
    public void modifyProvider(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String proCode = req.getParameter("proCode");
        String proName = req.getParameter("proName");
        String proContact = req.getParameter("proContact");
        String proPhone = req.getParameter("proPhone");
        String proAddress = req.getParameter("proAddress");
        String proFax = req.getParameter("proFax");
        String proDesc = req.getParameter("proDesc");
        String id = req.getParameter("id");

        // 后端验证：检查必填字段是否为空或只包含空格
        if (proContact == null || proContact.trim().isEmpty() ||
                proPhone == null || proPhone.trim().isEmpty() ||
                proAddress == null || proAddress.trim().isEmpty()) {

            // 设置错误信息
            req.setAttribute("error", "联系人、联系电话和联系地址不能为空或只包含空格！");

            // 将用户已填写的数据重新设置到request中，实现数据回显
            Provider providerBack = new Provider();
            providerBack.setId(Integer.valueOf(id));
            providerBack.setProCode(proCode != null ? proCode : "");
            providerBack.setProName(proName != null ? proName : "");
            providerBack.setProContact(proContact != null ? proContact : "");
            providerBack.setProPhone(proPhone != null ? proPhone : "");
            providerBack.setProAddress(proAddress != null ? proAddress : "");
            providerBack.setProFax(proFax != null ? proFax : "");
            providerBack.setProDesc(proDesc != null ? proDesc : "");

            req.setAttribute("provider", providerBack);
            req.getRequestDispatcher("providermodify.jsp").forward(req, resp);
            return;
        }

        Provider provider = new Provider();
        provider.setId(Integer.valueOf(id));
        provider.setProCode(proCode);
        provider.setProName(proName);
        provider.setProContact(proContact);
        provider.setProPhone(proPhone);
        provider.setProFax(proFax);
        provider.setProAddress(proAddress);
        provider.setProDesc(proDesc);
        provider.setModifyBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        provider.setModifyDate(new Date());

        boolean flag = false;
        providerService providerService = new providerServiceImpl();
        flag = providerService.modify(provider);

        if (flag) {
            resp.sendRedirect(req.getContextPath() + "/jsp/provider.do?method=query");
        } else {
            // 修改失败，设置错误信息并返回修改页面
            req.setAttribute("error", "修改供应商信息失败，请重试！");

            // 数据回显
            req.setAttribute("provider", provider);
            req.getRequestDispatcher("providermodify.jsp").forward(req, resp);
        }

    }

    // 根据proCode查询出Provider，在填写时，判断该供应商编码下的供应商是否存在，保证供应商编码唯一
    private void selectProCodeExist(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 判断供应商编码是否可用
        String proCode = request.getParameter("proCode");

        HashMap<String, String> resultMap = new HashMap<String, String>();
        // proCode 是空字符串或 null，直接认为该编码已存在（或不可用）
        if (StringUtils.isNullOrEmpty(proCode)) {
            // proCode == null || proCode.equals("")
            resultMap.put("proCode", "exist");
        } else {
            providerService providerService = new providerServiceImpl();
            Provider provider = providerService.selectProCodeExist(proCode);
            if (null != provider) {
                resultMap.put("proCode", "exist");
            } else {
                resultMap.put("proCode", "notexist");
            }
        }

        // 把resultMap转为json字符串以json的形式输出
        // 配置上下文的输出类型
        response.setContentType("application/json");
        // 从response对象中获取往外输出的writer对象
        PrintWriter outPrintWriter = response.getWriter();
        // 把resultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush(); // 刷新
        outPrintWriter.close(); // 关闭流
    }
}
